import socket
import cv2
import numpy as np

# 网络配置（需要与C++代码中的设置一致）
HOST = '0.0.0.0'  # 监听所有接口
PORT = 8080

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"等待连接在 {HOST}:{PORT}...")
    conn, addr = s.accept()
    print(f"已连接来自 {addr} 的客户端")

    with conn:
        while True:
            # 接收数据长度（4字节）
            len_data = conn.recv(4)
            if not len_data:
                break

            # 转换字节序（网络字节序 -> 主机字节序）
            img_size = int.from_bytes(len_data, byteorder='big')

            # 接收图像数据
            received = 0
            img_data = b''
            while received < img_size:
                chunk = conn.recv(min(4096, img_size - received))
                if not chunk:
                    break
                img_data += chunk
                received += len(chunk)

            # 解码并显示图像
            if len(img_data) == img_size:
                img_np = np.frombuffer(img_data, dtype=np.uint8)
                frame = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
                if frame is not None:
                    frame = cv2.resize(frame, (640, 480), interpolation=cv2.INTER_LINEAR)
                    cv2.imshow('Received Image', frame)
                    if cv2.waitKey(1) == 27:  # ESC键退出
                        break

cv2.destroyAllWindows()